package com.mathassistant.server.domain;

import java.util.ArrayList;

import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.listener.StoreCallback;

import com.mathassistant.shared.FinalTestDTO;

@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class FinalTest implements StoreCallback{
	@PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    @Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
	private String key;
	
	@Persistent(serialized = "true")
	private ArrayList<String> contentExam = new ArrayList<String>();
	
	@Persistent(serialized = "true")
	private ArrayList<String> anwserExam = new ArrayList<String>();

	@Persistent
	private Topic topicExamination;
	
	public FinalTest(){}
	public FinalTest(String contentExam, String anwserExam){
		this.setContentExam(convertString2ArrayList(contentExam));
		this.setAnwserExam(convertString2ArrayList(anwserExam));
	}
	public FinalTest(FinalTestDTO lesson){
		this.setContentExam(convertString2ArrayList(lesson.getContentExam()));
		this.setAnwserExam(convertString2ArrayList(lesson.getAnwserExam()));
	}
	
	public String getContentExam() {
		String t = "";
		for(String i : this.contentExam){
			t += i;
		}
		return t;
	}

	public void setContentExam(ArrayList<String> contentExam) {
		this.contentExam = contentExam;
	}

	public String getAnwserExam() {
		String t = "";
		for(String i : this.anwserExam){
			t += i;
		}
		return t;
	}

	public void setAnwserExam(ArrayList<String> anwserExam) {
		this.anwserExam = anwserExam;
	}

	public Topic getTopicExamination() {
		return topicExamination;
	}

	public void setTopicExamination(Topic topicExamination) {
		this.topicExamination = topicExamination;
	}

	public String getKey() {
		return key;
	}

	@Override
	public void jdoPreStore() {
		// TODO Auto-generated method stub
		
	}
	
	public FinalTestDTO toDTO(){
		return new FinalTestDTO(this.getKey(), this.getContentExam(), this.getAnwserExam());
	}
	
	public void updateFromDTO(FinalTestDTO exam){
		this.setContentExam(convertString2ArrayList(exam.getContentExam()));
		this.setAnwserExam(convertString2ArrayList(exam.getAnwserExam()));
	}
	
	public ArrayList<String> convertString2ArrayList(String convert){
		ArrayList<String> result = new ArrayList<String>();
		int length = convert.length();
		int i = 0;
		do{
			length -= 450;
			if(length <= 0){
				result.add(convert.substring(i));
				return result;
			}
			String t = convert.substring(i, i + 449);
			result.add(t);
			i += 450;
		} while (length > 0);
		return result;
	}
}
